#!/usr/bin/env python

import sys
import os
import re
from Tkinter import *

NOCASE = re.I #case insensitive flag

def NormQuit():
    sys.exit(0)

def getList():
    romlist.delete(0, END) #delete the contents of romlist
    d = rom.get() #get the directory
    keywords = search.get().split()
    fileList = os.listdir(d)
    fileList.sort()

    for file in fileList:
        if keywords:
            if matchesKeywords(file, keywords):
                romlist.insert(END, file)
        else:
            romlist.insert(END, file)
    
def matchesKeywords(file, keywords):
    for i in range(len(keywords)):
        keyword = keywords[i]

        if (re.search(keyword, file, NOCASE) and 
            i == len(keywords) - 1):
            return True
        elif re.search(keyword, file, NOCASE):
            continue
        else:
            break
    return False

def getList_withEvent(event): 
#the event argument is useless here.  
#Just call getList() and discard event
    getList()

def launchRom():
    romBasename = romlist.get(romlist.curselection())
    scale = '-nes.xscale ' + str(screensize.get()) + \
        ' -nes.yscale ' + str(screensize.get()) + ' '

    romFileName = '"' + os.path.join(rom.get(),
                                     romBasename) + '"'
    
    print 'mednafen ' + scale + romFileName
    os.system('mednafen ' + scale + romFileName)

root = Tk()
root.wm_title("Paul's MEDNAFEN frontend")

screensize=IntVar(value=2)
setControls=False

#The menus
mbar      = Menu(root)
file      = Menu(mbar)
options   = Menu(mbar)

#The user-input widgets
romlabel  = Label(root, text='Rom Path')
romsearch = Label(root, text='Regex keywords:')
rom       = Entry(root, width=100, relief='sunken')
search    = Entry(root, width=30,  relief='sunken')
updatelist= Button(root, text="Update File List", command=getList)

#The rom list
romlist   = Listbox(root, relief='raised')
scroll    = Scrollbar(root, command=romlist.yview)

#Launch widgets
launch    = Button(root, text='Start Emulation', command=launchRom)

romlist.config(yscrollcommand=scroll.set)
romlist.bind('<Double-Button-1>', launchRom)

rom.insert(0, '/home/paul/miscprograms/NESroms')
rom.bind('<Return>', getList_withEvent)
search.bind('<Return>', getList_withEvent)

mbar.add_cascade(label='File', menu=file, underline=0)
mbar.add_cascade(label='Options', menu=options, underline=0)

for i in range(4):
    i = i + 1
    options.add_radiobutton(label=str(i)+'x', variable=screensize, value=i)

options.add_separator()
options.add_checkbutton(label='Set Controls', variable=setControls)

file.add_command(label='Quit', underline=0, command=NormQuit)

root.config(menu=mbar)

romlabel.pack()
rom.pack()
romsearch.pack()
search.pack()
updatelist.pack()
scroll.pack(side=RIGHT, fill=Y)
romlist.pack(fill=BOTH)
launch.pack(side=TOP)

root.mainloop()
